//
//  MovingImageViewController.m
//  myDemo2
//
//  Created by wuxueying on 14-4-26.
//
//

#import "MovingImageViewController.h"
#import "SDWebImage/UIImageView+WebCache.h"

@interface MovingImageViewController ()
@end
@implementation MovingImageViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImageView *imageView = UIImageView.new;
    [imageView setContentMode:UIViewContentModeScaleAspectFill];
    [imageView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];
    NSInteger frameWidth = 320;
    NSInteger frameHeight = 320;
    imageView.frame = CGRectMake(0, 0, frameWidth, frameHeight);
    [self.view addSubview:imageView];
    __weak id weakSelf = self;
    __weak typeof(imageView)wImageView = imageView;
    [imageView setImageWithURL:[NSURL URLWithString:@"http://g.hiphotos.baidu.com/image/w%3D2048/sign=48d939820d2442a7ae0efaa5e57bac4b/f9198618367adab49c65184289d4b31c8701e47e.jpg"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
        [weakSelf setOffSetAnimation:wImageView Duration:10];
    }];
}

- (void)setOffSetAnimation:(UIImageView *)imageView Duration:(NSInteger)duration{
    NSInteger imageHeight = imageView.image.size.height;
    NSInteger imageWidth = imageView.image.size.width;
    NSInteger frameWidth = imageView.frame.size.width;
    NSInteger frameHeight = imageView.frame.size.height;
    NSInteger xOffSet = (frameHeight*imageWidth/imageHeight-frameWidth)/2;
    
    CAKeyframeAnimation *animation;
    animation = [CAKeyframeAnimation animationWithKeyPath:@"position.x"];
    animation.duration = duration;
    animation.repeatCount = HUGE_VALF;
    animation.values = [NSArray arrayWithObjects:
                        [NSNumber numberWithFloat:160.0f],
                        [NSNumber numberWithFloat:160 + xOffSet],
                        [NSNumber numberWithFloat:160.0f],
                        [NSNumber numberWithFloat:160 - xOffSet],
                        [NSNumber numberWithFloat:160.0f], nil];
    animation.removedOnCompletion = NO;
    [imageView.layer addAnimation:animation forKey:nil];
}

@end
